<?php
namespace App\Http\Controllers\Saas;

use App\Http\Config\ErrorCode;
use App\Library\UpTools;
use Carbon\Carbon;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class PermissionController extends BaseController
{
    public function __construct(Request $request)
    {
        parent::__construct($request);
    }

    //客户功能配置列表
    public function cusFunction(Request $request){
        if ($this->returnData['code'] > 0){
            return $this->returnData;
        }
        if (!$this->is_su){
            $this->returnData = ErrorCode::$admin_enum['params_error'];
            $this->returnData['msg'] = '无权限访问';
            return $this->return_result($this->returnData);
        }
        $page = $request->input('page',1);
        $page_size = $request->input('pageSize',30);
        $start = ($page - 1)*$page_size;
        $id = $request->input('cid','');
        $search = $request->input('search','');

        $res = DB::table('admin_permissions')->select('id','name','label','cid','display','description','show_mode as showMode');
        if ($id != ''){
            $res->where('cid',(int)$id);
        }
        if($search !=''){
            $res->where(function ($query) use ($search) {
                $query->where('name', 'LIKE', '%' . $search . '%')
                    ->orWhere('description', 'like', '%' . $search . '%')
                    ->orWhere('label', 'like', '%' . $search . '%');
            });
        }
        $data['count'] = $res->count();
        $data['currentPage'] = $page;
        $data['totalPage'] = ceil(($data['count'])/$page_size);
        $result = $res->skip($start)->take($page_size)->orderBy('id', 'asc')->get();
        $result = json_decode(json_encode($result),true);
        $data['list'] = $result;
        foreach ($data["list"] as &$item){
            $cus_res = DB::table('permissions')->where('mall_id', $request->mallId && $request->mallId != "undefined" ? request()->mallId : 1)->where("auth_id", $item["id"])->select("show_mode", "display", "cid")->first();
            if(!empty($cus_res)){
                $item["showMode"] = $cus_res->show_mode;
                if($cus_res->cid != '174' && $cus_res->cid != '183') {
                    $item["display"] = $cus_res->display;
                }else{
                    $item["display"] = 0;
                }
            }else{
                $item["display"] = 1;
                $item["showMode"] = 0;
            }
        }
        $this->returnData['data'] = $data;
        return $this->return_result($this->returnData);
    }

    public function openAllAuth(){
        if ($this->returnData['code'] > 0){
            return $this->returnData;
        }
        $mallId = request()->mallId;
        if(empty($mallId)){
            $this->returnData['code'] = 1;
            $this->returnData['msg'] = '系统ID不存在';
            return $this->returnData;
        }
        $data = DB::table('admin_permissions')->select('id','name','label','cid','display','description','show_mode')->get();
        if(!empty($data)){
            $data = json_decode(json_encode($data),true);
            foreach ($data as $item){
                $item["auth_id"] = $item["id"];
                $item["mall_id"] = $mallId;
                $cus_res = DB::table('permissions')->where('mall_id', $mallId)->where("auth_id", $item["id"])->first();
                unset($item["id"]);
                if ($cus_res){  //存在就修改
                    DB::table('permissions')->where('id', $cus_res->id)->update($item);
                }else{
                    $item["display"] = 0;
                    DB::table('permissions')->insert($item);
                }
            }
        }
        return $this->return_result($this->returnData);
    }

    //权限详情
    public function cusFunctionInfo($id){
        if ($this->returnData['code'] > 0){
            return $this->returnData;
        }
        $res = DB::table('admin_permissions')->where('id',$id)->first();
        if (!$res){
            $this->returnData['code'] = 1;
            $this->returnData['msg'] = '信息不存在';
        }else{
            $res = json_decode(json_encode($res),true);
            $this->returnData['data'] = $res;
        }
        return $this->return_result($this->returnData);
    }

    //编辑
    public function updateFunction(Request $request){
        if ($this->returnData['code'] > 0){
            return $this->returnData;
        }
        if (!$this->is_su){
            $this->returnData = ErrorCode::$admin_enum['params_error'];
            $this->returnData['msg'] = '无权限访问';
            return $this->return_result($this->returnData);
        }
        $id = $request->input('id','');
        $data['name'] = $request->input('name','');
        $data['label'] = $request->input('label','');
        $data['description'] = $request->input('description','');
        $data['cid'] = $request->input('cid','');
        $data['updated_at'] = Carbon::now()->toDateTimeString();
        $data["show_mode"] = 0;
        //修改客户端的权限信息
        $cus_res = DB::table('permissions')->where('mall_id', $request->mallId && $request->mallId != "undefined" ? request()->mallId : 1)->where("auth_id", $id)->first();
        if ($cus_res){  //存在就修改
            DB::table('permissions')->where('id',$cus_res->id)->update($data);
        }else{
            $data["mall_id"] = $request->mallId;
            $data["auth_id"] = $id;
            $data["display"] = 0;
            DB::table('permissions')->insert($data);
        }
        return $this->return_result($this->returnData);
    }

    //删除
    public function delFunction($id){
        if ($this->returnData['code'] > 0){
            return $this->returnData;
        }
        if (!$this->is_su){
            $this->returnData = ErrorCode::$admin_enum['params_error'];
            $this->returnData['msg'] = '无权限访问';
            return $this->return_result($this->returnData);
        }
        DB::table('permissions')->where("mall_id", \request()->mallId)->where("auth_id", $id)->delete();
        return $this->return_result($this->returnData);
    }

    //客户开启/关闭
    public function switchFunction(Request $request){
        if ($this->returnData['code'] > 0){
            return $this->returnData;
        }
        $id = $request->input('id','');
        $status = $request->input('status','');
        $target_info = DB::table('admin_permissions')->where('id',$id)->first();
        $target_info = json_decode(json_encode($target_info),true);
        if ($status == 1){  //开启
            if ($target_info['cid'] != 0){  //添加的如果是子 查询父
                $father_info = DB::table('permissions')->where('auth_id',$target_info['cid'])->where("mall_id", $request->mallId)->count();
                if (!$father_info){  //客户权限表没有父级就添加
                    $fathers = DB::table('admin_permissions')->where('id',$target_info['cid'])->first();
                    $fathers = json_decode(json_encode($fathers),true);
                    $fathers['display'] = 0;
                    $fathers["mall_id"] = $request->mallId;
                    $fathers["auth_id"] = $target_info['cid'];
                    $fathers["show_mode"] = 0;
                    unset($fathers["id"]);
                    DB::table('permissions')->insert($fathers);
                }
                //添加子
                $target_info['display'] = 0;
                $target_info["show_mode"] = 0;
                $target_info["mall_id"] = $request->mallId;
                $target_info["auth_id"] = $target_info['id'];
                unset($target_info["id"]);
                if(!DB::table('permissions')->where(['mall_id' => $request->mallId, "auth_id" => $target_info["auth_id"]])->update($target_info)) {
                    DB::table('permissions')->insert($target_info);
                }
            }else{  //添加父级 查询所有子集 批量添加
                $son_info = DB::table('admin_permissions')->where('cid',$target_info['id'])->get();
                $son_info = json_decode(json_encode($son_info),true);
                $target_info['display'] = 0;
                $target_info["show_mode"] = 0;
                $target_info["mall_id"] = $request->mallId;
                $target_info["auth_id"] = $target_info['id'];
                unset($target_info["id"]);
                if(!DB::table('permissions')->where(['mall_id' => $request->mallId, "auth_id" => $target_info["auth_id"]])->update($target_info)) {
                    DB::table('permissions')->insert($target_info);
                }
                foreach ($son_info as $v){
                    $v['display'] = 0;
                    $v["show_mode"] = 0;
                    $v["mall_id"] = $request->mallId;
                    $v["auth_id"] = $v['id'];
                    $id = $v["id"];
                    unset($v["id"]);
                    if(!DB::table('permissions')->where(['mall_id' => $request->mallId, "auth_id" => $id])->update($target_info)) {
                        DB::table('permissions')->insert($v);
                    }
                }
            }
        }elseif ($status == 2){  //关闭
            if ($target_info['cid'] != 0){  //关闭子
                DB::table('permissions')->where("mall_id", $request->mallId)->where("auth_id", $id)->delete();
            }else{  //关闭父集
                $res_list = DB::table('admin_permissions')->where('cid',$id)->get();
                $res_list = json_decode(json_encode($res_list),true);
                //删除父级修改父级状态
                DB::table('permissions')->where("mall_id", $request->mallId)->where("auth_id", $id)->delete();
                //删除子级修改子级状态
                foreach ($res_list as $v){
                    DB::table('permissions')->where("mall_id", $request->mallId)->where("auth_id", $v['id'])->delete();                             //删除功能
                }
            }
        }
        return $this->return_result($this->returnData);
    }

    //修改导航栏/插件显示
    public function updateMode(Request $request){
        if ($this->returnData['code'] > 0){
            return $this->return_result($this->returnData);
        }
        $id = $request->post('id','');
        $data['updated_at'] = Carbon::now()->toDateTimeString();
        $data['show_mode'] = $request->post('showMode','');
        $target_info = DB::table('admin_permissions')->where('id',$id)->first();
        $target_info = json_decode(json_encode($target_info),true);
        if ($target_info['cid'] == 0){
            $son_res = DB::table('admin_permissions')->where('cid',$id)->select('id')->get();
            if ($son_res){
                $son_res = json_decode(json_encode($son_res),true);
                foreach ($son_res as $v){
                    DB::table('permissions')->where("mall_id", $request->mallId)->where("auth_id", $v['id'])->update($data);
                }
            }
        }
        DB::table('permissions')->where("mall_id", $request->mallId)->where("auth_id", $id)->update($data);
        return $this->return_result($this->returnData);
    }
}
